package com.thread;

import java.util.ArrayList;
import java.util.List;

public class ListAdd2 {
	public volatile static List<String> list = new ArrayList<String>();
	
	void add(){
		list.add("");
	}
	
	int size(){
		return list.size();
	}
	
	public static void main(String[] args) {
		final ListAdd2 l1 = new ListAdd2();
		final Object lock = new Object();
		Thread t1 = new Thread(new Runnable() {
			
			public void run() {
				synchronized (lock) {
					for(int i =0 ;i<10;i++){
						l1.add();
						System.out.println(Thread.currentThread().getName() + ",添加了一个元素。。");
						if(l1.size() == 5){
							lock.notify();
						}
					}
				}
			}
		}, "t1");

		Thread t2 = new Thread(new Runnable() {
			
			public void run() {
				synchronized (lock) {
					if(l1.size() != 5){
						try {
							lock.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.out.println(Thread.currentThread().getName() + ",长度等于5，退出。。");
					throw new RuntimeException();
				}
			}
		}, "t2");
		
		t2.start();
		t1.start();
		
	}
}
